﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using HandBook.Data;
using System.Text;
using HandBook.Common;
using System.IO;

public partial class ManageRestaurants : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            InitAllData();
        }
    }

    private void InitAllData()
    {
        LoadGridView();
        FormatMenuTable();

        var loc = from l in HandBookData.EatDrinkDB.Locations
                  where l.LocationID == Convert.ToInt32((GridView1.Rows[0].FindControl("Label28") as Label).Text)
                  select l;
        foreach (var item in loc)
        {
            (GridView1.Rows[0].FindControl("Label28") as Label).Text = item.District;
        }
    }

    private void LoadGridView()
    {
        var restList = from r in HandBookData.EatDrinkDB.Restaurants
                       where r.RestID == 1
                       select r;
        GridView1.DataSource = restList;
        GridView1.DataBind();
    }

    private void FormatMenuTable()
    {
        //format RadEditor2
        var rest = HandBookData.EatDrinkDB.Restaurants.Single(r => r.RestID == 1);

        StringBuilder builder = new StringBuilder();
        builder.Append("<table width=\"663\">");
        builder.Append("<tr align=\"center\">");
        builder.Append("<td style=\"font-weight: bold; width: 331px\">Nhập vào tên món ăn ở đây</td>");
        builder.Append("<td style=\"font-weight: bold; width: 332px\">Nhập vào giá tiền tương ứng với món ăn ở đây</td>");
        builder.Append("</tr>");
        for (int i = 0; i < 1000; i++)
        {
            builder.Append("<tr align=\"center\">");
            builder.Append("<td>&nbsp;</td>");
            builder.Append("<td>&nbsp;</td>");
            builder.Append("</tr>");
        }
        builder.Append("</table>");

        if (rest.Menu == "")
        {
            RadEditor editor = GridView1.Rows[0].FindControl("RadEditor2") as RadEditor;
            editor.Content = builder.ToString();
        }
        else
        {
            RadEditor editor = GridView1.Rows[0].FindControl("RadEditor2") as RadEditor;
            editor.Content = rest.Menu;
        }

        //format RadEditorI2
        RadEditorI2.Content = builder.ToString();
    }
    protected void btnDoneEdit_Click(object sender, EventArgs e)
    {
        String[] files = Directory.GetFiles(Server.MapPath("Images/Temp"), "*.*");

        foreach (string file in files)
        {
            File.Delete(file);
        }

        Response.Redirect("ManageRestaurants.aspx");
    }
    protected void btnDesc_Click(object sender, EventArgs e)
    {
        var rest = HandBookData.EatDrinkDB.Restaurants.Single(r => r.RestID == 1);

        rest.ShortDescription = (GridView1.Rows[0].FindControl("txtShortDescription") as TextBox).Text.Trim();
        string content = (GridView1.Rows[0].FindControl("RadEditor1") as RadEditor).Content = (GridView1.Rows[0].FindControl("RadEditor1") as RadEditor).Content.Replace("Images/Temp/", "Images/Restaurants/" + rest.ImageFolderName + "/");
        rest.LongDescription = content;

        HandBookData.EatDrinkDB.SubmitChanges();

        String[] files = Directory.GetFiles(Server.MapPath("Images/Temp"), "*.*");

        foreach (string file in files)
        {
            string[] array = file.Split('\\');
            string destfile = Path.Combine(Server.MapPath("Images/Restaurants/" + rest.ImageFolderName + "/"), array[array.Length - 1]);
            if (content.Contains(array[array.Length - 1]))
            {
                File.Copy(file, destfile, true);
            }
        }

        InitAllData();

        ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Thông tin đã được cập nhật')</script>");
    }
    protected void btnInfo_Click(object sender, EventArgs e)
    {
        var rest = HandBookData.EatDrinkDB.Restaurants.Single(r => r.RestID == 1);

        string name = rest.RestName = (GridView1.Rows[0].FindControl("txtRestName") as TextBox).Text.Trim();
        rest.RestCat = (GridView1.Rows[0].FindControl("txtRestStyle") as TextBox).Text.Trim();
        rest.Address = (GridView1.Rows[0].FindControl("txtRestAddress") as TextBox).Text.Trim();
        rest.AddressDescription = (GridView1.Rows[0].FindControl("txtRestAddressDesc") as TextBox).Text.Trim();
        rest.Slogan = (GridView1.Rows[0].FindControl("txtRestSlogan") as TextBox).Text.Trim();
        rest.LocationID = Convert.ToInt32((GridView1.Rows[0].FindControl("ddlRestLoc") as RadComboBox).SelectedValue);
        rest.PhoneNumber = (GridView1.Rows[0].FindControl("txtRestPhone") as TextBox).Text.Trim();
        rest.Email = (GridView1.Rows[0].FindControl("txtRestEmail") as TextBox).Text.Trim();
        rest.Fax = (GridView1.Rows[0].FindControl("txtRestFax") as TextBox).Text.Trim();
        rest.Website = (GridView1.Rows[0].FindControl("txtRestWebsite") as TextBox).Text.Trim();
        rest.SeatCount = (GridView1.Rows[0].FindControl("txtRestSeats") as TextBox).Text.Trim();
        rest.IsOrder = (GridView1.Rows[0].FindControl("txtRestIsOrder") as TextBox).Text.Trim();
        rest.OffDate = (GridView1.Rows[0].FindControl("txtOffDate") as TextBox).Text.Trim();
        rest.ServedTime = (GridView1.Rows[0].FindControl("txtRestServedTime") as TextBox).Text.Trim();
        rest.PaymentType = (GridView1.Rows[0].FindControl("txtRestPayment") as TextBox).Text.Trim();
        rest.Language = (GridView1.Rows[0].FindControl("txtRestLanaguage") as TextBox).Text.Trim();
        rest.AveragePrice = (GridView1.Rows[0].FindControl("txtRestAvaragePrice") as TextBox).Text.Trim();
        rest.SubServices = (GridView1.Rows[0].FindControl("txtRestService") as TextBox).Text.Trim();
        rest.Note = (GridView1.Rows[0].FindControl("txtRestNote") as TextBox).Text.Trim();

        HandBookData.EatDrinkDB.SubmitChanges();

        InitAllData();

        ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Thông tin đã được cập nhật')</script>");
    }

    protected void btnMenu_Click(object sender, EventArgs e)
    {
        var rest = HandBookData.EatDrinkDB.Restaurants.Single(r => r.RestID == 1);

        rest.Menu = (GridView1.Rows[0].FindControl("RadEditor2") as RadEditor).Content;

        HandBookData.EatDrinkDB.SubmitChanges();

        InitAllData();

        ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Thông tin đã được cập nhật')</script>");
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        bool flag = false;
        var rest = HandBookData.EatDrinkDB.Restaurants.Single(r => r.RestID == 1);

        string folderName = string.Empty;

        if (rest.ImageFolderName == null || rest.ImageFolderName == string.Empty)
        {
            folderName = "blank";
        }
        else
        {
            folderName = rest.ImageFolderName;
        }

        if (FileManager.CheckDirectoryExisting(Server.MapPath("Images/Restaurants/" + folderName)))
        {
            flag = UploadImage(flag, rest, folderName);
            if (flag == true)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Upload hình thành công!')</script>");
            }
        }
        else
        {
            if (folderName != "blank")
            {
                Directory.CreateDirectory(Server.MapPath("Images/Restaurants/" + rest.ImageFolderName));
                flag = UploadImage(flag, rest, folderName);
                if (flag == true)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Upload hình thành công!')</script>");
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Thư mục hình của nhà hàng này chưa có trong cơ sở dữ liệu.\tVui lòng nhập tên thư mục chứa hình của nhà hàng trước khi thực hiện việc upload hình!')</script>");
            }
        }
    }

    private bool UploadImage(bool flag, Restaurant rest, string folderName)
    {
        //upload Logo
        RadUpload RadUpload1 = GridView1.Rows[0].FindControl("RadUpload1") as RadUpload;
        if (RadUpload1.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName().Replace(validFile.GetName(), "logo.gif")), true);
            }
            flag = true;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Hình Logo không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        //upload Banner
        RadUpload RadUpload2 = GridView1.Rows[0].FindControl("RadUpload2") as RadUpload;
        if (RadUpload2.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUpload2.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName().Replace(validFile.GetName(), "banner.gif")), true);
            }
            flag = true;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Hình Banner không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        //upload Flash
        RadUpload RadUpload3 = GridView1.Rows[0].FindControl("RadUpload3") as RadUpload;
        if (RadUpload3.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUpload3.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName().Replace(validFile.GetName(), "flash.swf")), true);
                rest.Flash = "~/Images/Restaurants/flash.swf";
                HandBookData.EatDrinkDB.SubmitChanges();
            }
            flag = true;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Flash không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        //upload hình minh họa
        RadUpload RadUpload4 = GridView1.Rows[0].FindControl("RadUpload4") as RadUpload;
        if (RadUpload4.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUpload4.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName()), true);
            }
            flag = true;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Hình minh họa không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }
        return flag;
    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        Restaurant rest = new Restaurant();

        //lấy thông tin phần "Thông tin nhà hàng"
        string restName = rest.RestName = txtIRestName.Text.Trim();

        Directory.CreateDirectory(Server.MapPath("Images/Restaurants/" + restName + DateTime.Now.ToString("_dd_MM_yy_hh_mm_ss")));
        string folderName = restName + DateTime.Now.ToString("_dd_MM_yy_hh_mm_ss");

        rest.RestCat = txtIRestStyle.Text.Trim();
        rest.Address = txtIRestAddress.Text.Trim();
        rest.AddressDescription = txtIRestAddressDesc.Text.Trim();
        rest.Slogan = txtIRestSlogan.Text.Trim();
        rest.LocationID = Convert.ToInt32(ddlIRestLoc.SelectedValue);
        rest.PhoneNumber = txtIRestPhone.Text.Trim();
        rest.Email = txtIRestEmail.Text.Trim();
        rest.Fax = txtIRestFax.Text.Trim();
        rest.Website = txtIRestWebsite.Text.Trim();
        rest.SeatCount = txtIRestSeats.Text.Trim();
        rest.IsOrder = txtIRestIsOrder.Text.Trim();
        rest.OffDate = txtIRestOffDate.Text.Trim();
        rest.ServedTime = txtIRestServedTime.Text.Trim();
        rest.PaymentType = txtIRestPayment.Text.Trim();
        rest.Language = txtIRestLanaguage.Text.Trim();
        rest.AveragePrice = txtIRestAvaragePrice.Text.Trim();
        rest.SubServices = txtIRestService.Text.Trim();
        rest.Note = txtIRestNote.Text.Trim();

        //lấy thông tin phần mô tả
        rest.ShortDescription = txtIShortDescription.Text.Trim();
        string content = RadEditorI1.Content = RadEditorI1.Content.Replace("Images/Temp/", "Images/Restaurants/" + folderName + "/");
        rest.LongDescription = content;

        String[] files = Directory.GetFiles(Server.MapPath("Images/Temp"), "*.*");

        foreach (string file in files)
        {
            string[] array = file.Split('\\');
            string destfile = Path.Combine(Server.MapPath("Images/Restaurants/" + folderName + "/"), array[array.Length - 1]);
            if (content.Contains(array[array.Length - 1]))
            {
                File.Copy(file, destfile, true);
            }
        }

        //lấy thông tin phần menu

        rest.Menu = RadEditorI2.Content;

        //upload hình

        //upload Logo
        if (RadUploadI1.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUploadI1.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName().Replace(validFile.GetName(), "logo.gif")), true);
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Hình Logo không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        //upload Banner
        if (RadUploadI2.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUploadI2.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName().Replace(validFile.GetName(), "banner.gif")), true);
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Hình Banner không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        //upload Flash
        if (RadUploadI3.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUploadI3.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName().Replace(validFile.GetName(), "flash.swf")), true);
                rest.Flash = "~/Images/Restaurants/flash.swf";
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Flash không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        //upload hình minh họa
        if (RadUploadI4.UploadedFiles.Count > 0)
        {
            foreach (UploadedFile validFile in RadUploadI4.UploadedFiles)
            {
                string targetFolder = Server.MapPath("Images/Restaurants/" + folderName);
                validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName()), true);
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Info", "<script>alert('Hình minh họa không đúng định dạng hoặc vượt quá dung lượng cho phép.\nXin vui lòng kiểm tra lại!')</script>");
        }

        rest.ImageFolderName = folderName;

        HandBookData.EatDrinkDB.Restaurants.InsertOnSubmit(rest);
        HandBookData.EatDrinkDB.SubmitChanges();

        Response.Redirect("ManageRestaurants.aspx");
    }
}